package socketHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
 * 
 * @author Peter Steiner & Fredrik Wallenius
 *
 */
public class MySocket {
	
		public static final int SERVER_PORT = 4444;
		private BufferedReader in = null;
		private PrintWriter out;
		private Socket sock;
		private clientData data;
		
		
		public MySocket(String[] args) throws IOException{
			data = new clientData();
			if(args.length != 1) {
				System.out.println("[Client Usage]: tcp_client hostname");
				System.exit(0);
			}
			sock = null;
			try {
				InetAddress serverAddr = InetAddress.getByName(args[0]);
				sock = new Socket(serverAddr, SERVER_PORT);
			}
			finally {
				try {
					if(sock == null)
					System.out.println("[Client]: Couldn't bind socket..");
					else
					System.out.println("[Client]: Socket running..");
				}catch(Exception e) {}
			}
		
			in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));	
		}
		
		public void serverHandshake(){
			
			Protocoll.processInput(readSocket(), data);
			
			writeToSocket(Protocoll.processSYNC(data));
			
			Protocoll.processInput(readSocket(), data);
			
			Protocoll.processInput(readSocket(), data);
			
			writeToSocket(Protocoll.processACKD(data));
						
			writeToSocket(Protocoll.processNAME(data.getUserName()));
		}
		
		public clientData getData(){
			return data;
		}
	
		public void writeToSocket(String text){
				out.println(text);
				out.flush();
		}
		
		public String readSocket(){
				String text = null;
				try {
					text = in.readLine();
				} catch (IOException e) {
					System.out.println("[Client]: Could not read line...");
					e.printStackTrace();
				}
				return text;
		}
}
